package org.jsola.hr.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.jsola.core.Page;
import org.jsola.exception.ParamException;
import org.jsola.hr.common.ExampleKit;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dao.IPersonalEventDAO;
import org.jsola.hr.dto.PersonalEventAddDTO;
import org.jsola.hr.dto.PersonalEventUpdateDTO;
import org.jsola.hr.entity.EmpInfoDO;
import org.jsola.hr.entity.PersonalEventDO;
import org.jsola.hr.query.PersonalEventQuery;
import org.jsola.hr.service.ICompanyService;
import org.jsola.hr.service.IEmpInfoService;
import org.jsola.hr.service.IPersonalEventService;
import org.jsola.hr.vo.*;
import org.jsola.user.core.TokenUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 人事变动表
 *
 * @author ds
 */
@Service("hrPersonalEventServiceImpl")
@Slf4j
public class PersonalEventServiceImpl implements IPersonalEventService {

    @Autowired
    private IPersonalEventDAO personalEventDAO;

    @Autowired
    private ICompanyService companyService;

    @Autowired
    private IEmpInfoService empInfoService;


    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public PersonalEventVO save(PersonalEventAddDTO personalEventAddDTO, TokenUser tokenUser) {
        // 转DO
        PersonalEventDO personalEventDO = personalEventAddDTO.to(PersonalEventDO.class);
        // 保存
        personalEventDO.setUserId(tokenUser.getUserId());
        personalEventDO = save(personalEventDO, tokenUser.getSiteId(), tokenUser.getUserId());
        return personalEventDO.to(PersonalEventVO.class);
    }

    @Override
    public Integer onlySave(PersonalEventDO personalEventDO) {

        return personalEventDAO.insert(personalEventDO);

    }


    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public void autoSave(EmpInfoVO empInfoVO, TokenUser tokenUser, String desc, String eventType, String eventName) {
        // 根据不同的节点自动添加至系统
        PersonalEventDO personalEventDO = new PersonalEventDO();
        personalEventDO.setIfAuto(true);
        personalEventDO.setEventTime(new Date());
        personalEventDO.setEventType(eventType);
        personalEventDO.setCompanyId(empInfoVO.getCompanyId());
        personalEventDO.setEmpId(empInfoVO.getId());
        personalEventDO.setDescription(desc);
        personalEventDO.setUserId(empInfoVO.getUserId());
        personalEventDO.setEventName(eventName);


        // 保存
        save(personalEventDO, tokenUser.getSiteId(), tokenUser.getUserId());
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public void autoSaveList(List<EmpInfoVO> empInfoVOList, String desc, String eventType, String eventName, TokenUser tokenUser) {
        List<PersonalEventDO> list = new ArrayList<>();
        for (EmpInfoVO empInfoVO : empInfoVOList) {
            // 根据不同的节点自动添加至系统
            PersonalEventDO personalEventDO = new PersonalEventDO();
            personalEventDO.preInsert(tokenUser.getUserId());
            personalEventDO.setIfAuto(true);
            personalEventDO.setEventTime(new Date());
            personalEventDO.setEventType(eventType);
            personalEventDO.setCompanyId(empInfoVO.getCompanyId());
            personalEventDO.setEmpId(empInfoVO.getId());
            personalEventDO.setDescription(desc);
            personalEventDO.setUserId(empInfoVO.getUserId());
            personalEventDO.setSiteId(tokenUser.getSiteId());
            personalEventDO.setEventName(eventName);
            list.add(personalEventDO);
        }
        personalEventDAO.insertListAndSetId(list);
    }

    public void save() {


    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int update(PersonalEventUpdateDTO personalEventUpdateDTO, TokenUser tokenUser) {
        //转DO
        PersonalEventDO personalEventDO = personalEventUpdateDTO.to(PersonalEventDO.class);
        //根据主键更新，只更新非null值
        return updateByIdSelective(personalEventDO, tokenUser.getSiteId(), tokenUser.getUserId());
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int deleteByIds(TokenUser tokenUser, Long... personalEventIds) {

        return deleteByIds(tokenUser.getSiteId(), tokenUser.getUserId(), (Object[]) personalEventIds);
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int deleteById(TokenUser tokenUser, Long personalEventIds) {
        PersonalEventDO personalEventDO = selectDOById(personalEventIds, tokenUser.getSiteId());
        if (personalEventDO.getIfAuto()) {
            throw new ParamException("删除失败，系统自动录入不支持删除");
        }
        return deleteByIds(tokenUser.getSiteId(), tokenUser.getUserId(), personalEventIds);
    }


    @Override
    public PersonalEventVO selectById(Long personalEventId, String siteId) {
        PersonalEventDO personalEventDO = selectDOById(personalEventId, siteId);
        if (personalEventDO == null) {
            return null;
        }
        return personalEventDO.to(PersonalEventVO.class);
    }

    @Override
    public List<PersonalEventListVO> select(PersonalEventQuery personalEventQuery, String siteId) {
        List<PersonalEventDO> personalEventDOList = selectDO(personalEventQuery, siteId);
        if (CollectionUtils.isEmpty(personalEventDOList)) {
            return personalEventDOList == null ? null : new ArrayList<>();
        }
        return personalEventDOList.stream()
                .map(personalEventDO -> personalEventDO.to(PersonalEventListVO.class))
                .collect(Collectors.toList());
    }

    @Override
    public int selectCount(PersonalEventQuery personalEventQuery, String siteId) {
        Example example = buildExample(personalEventQuery, siteId);
        return personalEventDAO.selectCountByExample(example);
    }

    @Override
    public Page<PersonalEventListVO> selectPage(PersonalEventQuery personalEventQuery, String siteId) {
        Example example = buildExample(personalEventQuery, siteId);
        Page<PersonalEventDO> page = personalEventDAO.selectPageByExample(example,
                personalEventQuery.getPageNo(),
                personalEventQuery.getPageSize());

        return page.to(PersonalEventListVO.class);
    }

    @Override
    public PersonalEventDO selectDOById(Long personalEventId, String siteId) {
        return listById(personalEventId, siteId);
    }

    @Override
    public List<PersonalEventDO> selectDO(PersonalEventQuery personalEventQuery, String siteId) {
        Example example = buildExample(personalEventQuery, siteId);
        return personalEventDAO.selectByExample(example);
    }


    /**
     * 根据查询参数，构建example
     *
     * @param personalEventQuery 查询参数
     * @param siteId             所属站点id
     * @return example
     */
    private Example buildExample(PersonalEventQuery personalEventQuery, String siteId) {
        Example example = new Example(PersonalEventDO.class);
        example.and()
                .andEqualTo("siteId", siteId);
        if (personalEventQuery.getUserId() != null) {
            example.and().andEqualTo("userId", personalEventQuery.getUserId());
        }
        if (personalEventQuery.getCompanyId() != null) {
            example.and().andEqualTo("companyId", personalEventQuery.getCompanyId());
        }
        if (personalEventQuery.getIfAuto() != null) {
            example.and().andEqualTo("ifAuto", personalEventQuery.getIfAuto());
        }
        if (personalEventQuery.getEventName() != null) {
            example.and().andEqualTo("eventName", personalEventQuery.getEventName());
        }
        if (personalEventQuery.getEventType() != null) {
            example.and().andEqualTo("eventType", personalEventQuery.getEventType());
        }
        if (personalEventQuery.getCompanyName() != null) {
            example.and().andLike("companyName", "%" + personalEventQuery.getCompanyName() + "%");
        }
        if (personalEventQuery.getEventTimeStart() != null &&
                personalEventQuery.getEventTimeEnd() != null) {
            example.and().andBetween("eventTime", personalEventQuery.getEventTimeStart(),
                    personalEventQuery.getEventTimeEnd());
        }
        if (personalEventQuery.getEmpId() != null) {
            example.and().andEqualTo("empId", personalEventQuery.getEmpId());
        }
        // 排序
        ExampleKit.setExampleOrder(example, personalEventQuery.getOrders());
        return example;
    }

    @Override
    public List<PersonalEventResultByYearVO> selectByEmpId(String empId, TokenUser tokenUser) {
        List<PersonalEventResultByYearVO> resultList = new ArrayList<>();
        List<String> getEventTimeListByYear = personalEventDAO.getEventTimeListByYear(empId);
        getEventTimeListByYear.forEach(year -> {
            List<String> getEventTimeList = personalEventDAO.getEventTimeList(empId, year);
            if (getEventTimeList.size() > 0) {
                List<PersonalEventResultVO> resultListByDay = new ArrayList<>();
                getEventTimeList.forEach(time -> {
                    List<PersonalEventListVO> eventByTimeList = personalEventDAO.getEventListByEventTime(time, empId);
                    for (PersonalEventListVO personalEventListVO : eventByTimeList) {
                        // 公司名称未保存 取公司Id
                        if (personalEventListVO.getCompanyName() == null) {
                            if (personalEventListVO.getCompanyId() != null) {
                                CompanyVO companyVO = companyService.selectBaseCompanyById(personalEventListVO
                                        .getCompanyId(), tokenUser.getSiteId());
                                if (companyVO != null) {
                                    personalEventListVO.setDescription(personalEventListVO.getDescription()
                                            + "[" + companyVO.getName() + "]");
                                }
                            }
                        } else {
                            personalEventListVO.setDescription(personalEventListVO.getDescription()
                                    + "[" + personalEventListVO.getCompanyName() + "]");
                        }
                        String description = personalEventListVO.getDescription();
                        if (description.contains("合同编号为:null,,")) {
                            String[] splitDescriptions = description.split("合同编号为:null,,");
                            StringBuilder stringBuilder = new StringBuilder();
                            for (String splitDescription : splitDescriptions) {
                                stringBuilder.append(splitDescription);
                            }
                            personalEventListVO.setDescription(stringBuilder.toString());
                        }
                    }
                    PersonalEventResultVO result = new PersonalEventResultVO();
                    result.setEventByDay(eventByTimeList);
                    //result.setEventTime(DateUtils.parseDate(time,"yyyy-MM-dd"));
                    result.setEventTime(time);

                    resultListByDay.add(result);

                });
                PersonalEventResultByYearVO resultByYear = new PersonalEventResultByYearVO();

                resultByYear.setEventTime(year);
                resultByYear.setEventByYear(resultListByDay);
                resultList.add(resultByYear);

            }
        });
        return resultList;
    }

    @Override
    public List<PersonalEventDO> selectDoByEmpId(String empId, TokenUser tokenUser) {
        Example example = new Example(PersonalEventDO.class);
        example.and()
                .andEqualTo("empId", empId)
                .andEqualTo("siteId", tokenUser.getSiteId());
        return personalEventDAO.selectByExample(example);
    }

//    @Override
//    public List<PersonalEventResultByYearVO> selectByUserId(String userId, TokenUser tokenUser) {
//        List<PersonalEventResultByYearVO> resultList = new ArrayList<>();
//        List<String> getEventTimeListByYear = personalEventDAO.getEventTimeListByUserId(userId);
//        getEventTimeListByYear.forEach(year -> {
//            List<String> getEventTimeList = personalEventDAO.getEventTimeListByUserIdAndYear(userId, year);
//            if (getEventTimeList.size() > 0) {
//                List<PersonalEventResultVO> resultListByDay = new ArrayList<>();
//                getEventTimeList.forEach(time -> {
//                    List<PersonalEventListVO> eventByTimeList = personalEventDAO.getEventListByUserId(time, userId);
//                    for (PersonalEventListVO personalEventListVO : eventByTimeList) {
//                        // 公司名称未保存 取公司Id
//                        if (personalEventListVO.getCompanyName() == null) {
//                            if (personalEventListVO.getCompanyId() != null) {
//                                CompanyVO companyVO = companyService.selectById(personalEventListVO.getCompanyId(), tokenUser);
//                                if (companyVO != null) {
//                                    personalEventListVO.setDescription(personalEventListVO.getDescription()
//                                            + "[" + companyVO.getName() + "]");
//                                }
//                            }
//                        } else {
//                            personalEventListVO.setDescription(personalEventListVO.getDescription()
//                                    + "[" + personalEventListVO.getCompanyName() + "]");
//                        }
//                        String description = personalEventListVO.getDescription();
//                        if (description.contains("合同编号为:null,,")) {
//                            String[] splitDescriptions = description.split("合同编号为:null,,");
//                            StringBuilder stringBuilder = new StringBuilder();
//                            for (String splitDescription : splitDescriptions) {
//                                stringBuilder.append(splitDescription);
//                            }
//                            personalEventListVO.setDescription(stringBuilder.toString());
//                        }
//                    }
//                    PersonalEventResultVO result = new PersonalEventResultVO();
//                    result.setEventByDay(eventByTimeList);
//                    //result.setEventTime(DateUtils.parseDate(time,"yyyy-MM-dd"));
//                    result.setEventTime(time);
//
//                    resultListByDay.add(result);
//
//                });
//                PersonalEventResultByYearVO resultByYear = new PersonalEventResultByYearVO();
//
//                resultByYear.setEventTime(year);
//                resultByYear.setEventByYear(resultListByDay);
//                resultList.add(resultByYear);
//
//            }
//        });
//        return resultList;
//    }
}




